<?php defined('SYSPATH') OR die('No direct access allowed.');

// version 0.1

class Autocompleter_Plugin extends WB_FormItem {

	var $field, $table, $primary_key, $table_alias, $col_alias;
	var $url_or_data;
	var $options;
	var $result;
	
	public function __construct($name='', $params=array())
	{
		parent::__construct($name, $params);
		
		//From DbDropDown
		$this->primary_key = isset($this->params['primary_key']) ? $this->params['primary_key'] : 'id';
		$this->table = isset($this->params['table']) ? $this->params['table'] : $this->db_table;
		$this->field = isset($this->params['field']) ? $this->params['field'] : '';
		$this->table_alias = isset($this->params['table_alias']) ? $this->params['table_alias'] : $this->table;
		$this->col_alias = isset($this->params['col_alias']) ? $this->params['col_alias'] : $this->field;

		//Autocompleter special 
		if (empty($this->params['url_or_data'])) throw new Kohana_Exception ('autocompleter_plugin.no_url_or_data');
		else $this->url_or_data = $this->params['url_or_data'];
		
		if ( ! empty($this->params['base_or_site']))
			$this->url_or_data = $this->params['base_or_site']=='base' ?
					url::base().$this->url_or_data :
					url::site($this->url_or_data);
		
		$this->options = empty($params['options']) ? null : $params['options'];
		$this->result = empty($this->params['result']) ? null : $this->params['result'];
		
		if ($this->field)
		{
			$this->table_columns[$this->col_alias] = $this->table.'.'.$this->field;
			$this->table_joins[$this->table_alias] = array($this->table, $this->table.'.'.$this->primary_key.'='.$this->db_table.'.'.$this->name);
		}
		
		Event::add('wb_controller.pre_render_form', array($this, 'init_form'));
	}
	
	/**
	 * Returns html value for a table cell
	 * 
	 * @return string
	 */
	public function render_cell()
	{
		$value = $this->value[$this->col_alias];
		return empty($value) ? '&nbsp;' : $value;
	}
	
	/**
	 * Renders the form element
	 * 
	 * @return string
	 */
	public function render_item()
	{
		$dbval = empty($this->table) ? $this->value : $this->get_shown_data();
		
		$str = $this->prefix;
		$str .= form::label($this->name, $this->label);
		$str .= form::input($this->name.'_auto', $dbval, html::attributes($this->attributes));
		$str .= '<input type="hidden" name="'.$this->name.'" id="'.$this->name.'" value="'.$this->value.'" />';
		$str .= $this->suffix;
		
		return $str;
	}
	
	private function _get_js_template()
	{
		$template = '
var NAME;
var NAME_auto;

function NAMEResult(event, data, formatted)
{
	NAME.val(data[2]);
	NAME_auto.blur();
}
$(document).ready(function(){
	NAME = $("#NAME");
	NAME_auto = $("#NAME_auto");	
	NAME_auto.autocomplete
		(
			"'.$this->url_or_data.'",
			'.json_encode($this->options).'
		)
		'.(empty($this->result) ? '' : '.result(NAMEResult)').';
});
';
		return str_replace('NAME', $this->name, $template);		
	}
	
	function init_form()
	{
		Kohana::instance()->wb_template->css('autocompleter_plugin', 'plugins/jquery.autocomplete.css');
		Kohana::instance()->wb_template->js('plugins/jquery.autocomplete.pack');
		Kohana::instance()->wb_template->script($this->name.'Autocompleter', $this->_get_js_template());
	}
	
	function get_shown_data()
	{
		$field = $this->field;
		$query = Kohana::instance()->db
				->select($field)
				->from($this->table)
				->where($this->primary_key, $this->value)
				->get();
		if ($query->count()) return $query->current()->$field;
		else return '';
	}
}

//End of Autocompleter_Plugin Library